package org.example.msmservice.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.example.ResultCode.R;
import org.example.msmservice.service.MsmService;
import org.example.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private MsmService msmService;
    @GetMapping("send/{phone}")//发送信息
    public R sendMsm(@PathVariable String phone){
        //从redis获取验证嘛，获取不到就让阿里云发送
        String code=redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){return  R.ok();}
        //生成4wei随机数
          code= RandomUtil.getFourRandom();
        Map<String,Object> param=new HashMap<>();
        param.put("code",code);
        boolean issend=msmService.send(param,phone);
        if (issend){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);//验证码在redis中的时间
            return  R.ok();}
        else {
            return R.error().message("发送失败");}
    }

}
